package cn.fboost.mtos.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class FileUtil {
    public static final HashMap<String, String> FILE_TYPE_MAP = new HashMap<>() {
        {
            put("FFD8FFE0", "jpg");
            put("FFD8FFE1", "jpg");
            put("FFD8FFE8", "jpg");

            put("89504E47", "png");
            put("47494638", "gif");
            put("52494646", "webp");
        }
    };

    public static String getFileHeader(MultipartFile file) {
        InputStream is = null;
        String value = null;
        try {
            is = file.getInputStream();
            byte[] b = new byte[4];
            is.read(b, 0, b.length);

            value = bytesToHexString(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return value;
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length == 0) {
            return null;
        }

        String hv;
        for (byte b : src) {
            hv = Integer.toHexString(b & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }

        return builder.toString();
    }
}
